//
//  UpImagesCell.m
//  FMRecordVideo
//
//  Created by 高波 on 2019/4/16.
//  Copyright © 2019 SF. All rights reserved.
//

#import "UpImagesCell.h"
#import <QCloudCOSXML/QCloudCOSXML.h>
#import <QCloudCore/QCloudCore.h>
#import <AdSupport/AdSupport.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#import "TXUGCPublish.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import <Photos/Photos.h>
@interface UpImagesCell() <TXVideoPublishListener>
{
    TXUGCPublish *_videoPublish;
}

@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIImageView *doneBtn;
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
@property (weak, nonatomic) IBOutlet UIImageView *logo;
@property (weak, nonatomic) IBOutlet UILabel *typeDes;


@end

@implementation UpImagesCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.bgView.layer.cornerRadius = 5.0f;
    self.bgView.clipsToBounds = YES;
    self.doneBtn.hidden = YES;
    self.progressLabel.hidden = NO;
}

- (void)setType:(mediaType)type
{
    _type = type;
    if (type == mediaVideo) {
        self.logo.image = [UIImage imageNamed:@"uploadVideo"];
        self.typeDes.text = @"视频文件上传中...";
    }else if(type == mediaPhoto) {
        self.logo.image = [UIImage imageNamed:@"ts-imagepng"];
        self.typeDes.text = @"图片文件上传中...";
    }else {
        self.logo.image = [UIImage imageNamed:@"audio"];
        self.typeDes.text = @"音频文件上传中...";
    }
}

#pragma mark -- 图片
- (void)setImage:(UIImage *)image
{
    _image = image;
    
    QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
    NSString *fileName = [self fileKey];
    NSLog(@"%@",fileName);
    put.object = self.key;
    put.bucket = self.bucket;
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    
    put.body = imageData;
    [put setSendProcessBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"upload %lld totalSend %lld aim %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *precent = [NSString stringWithFormat:@"%.2f",(CGFloat)totalBytesSent/totalBytesExpectedToSend];
            NSInteger intValue = [precent floatValue] * 100;
            self.progressLabel.text = [NSString stringWithFormat:@"%ld%%",(long)intValue];
            [self.progressView setProgress:(CGFloat)totalBytesSent/totalBytesExpectedToSend animated:YES];
        });
        
    }];
    [put setFinishBlock:^(id outputObject, NSError* error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            QCloudUploadObjectResult *result = (QCloudUploadObjectResult *)outputObject;
            NSLog(@"location:%@",result.location);
            
            [self.progressView setProgress:1 animated:YES];
            
            self.progressLabel.hidden = YES;
            self.doneBtn.hidden = NO;
        });
    }];
    [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
}

#pragma mark -- mp3
- (void)setMp3Url:(NSURL *)mp3Url
{
    _mp3Url = mp3Url;
    
    QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
    put.object = self.key;
    put.bucket = self.bucket;
    
    NSData *mp3Data = [NSData dataWithContentsOfURL:mp3Url];
    put.body = mp3Data;
    [put setSendProcessBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"upload %lld totalSend %lld aim %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *precent = [NSString stringWithFormat:@"%.2f",(CGFloat)totalBytesSent/totalBytesExpectedToSend];
            NSInteger intValue = [precent floatValue] * 100;
            self.progressLabel.text = [NSString stringWithFormat:@"%ld%%",(long)intValue];
            [self.progressView setProgress:(CGFloat)totalBytesSent/totalBytesExpectedToSend animated:YES];
        });
        
    }];
    [put setFinishBlock:^(id outputObject, NSError* error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            QCloudUploadObjectResult *result = (QCloudUploadObjectResult *)outputObject;
            NSLog(@"location:%@",result.location);
            
            [self.progressView setProgress:1 animated:YES];
            
            self.progressLabel.hidden = YES;
            self.doneBtn.hidden = NO;
        });
    }];
    [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
}

#pragma mark -- 视频
- (void)setSign:(NSString *)sign
{
    _sign = sign;
    if (!_videoPublish) {
        _videoPublish = [[TXUGCPublish alloc] initWithUserID:@"carol_ios"];
    }
    _videoPublish.delegate = self;
    
    [self getCover:0 videoUrl:self.videoUrl compelete:^(UIImage *objectID) {
        TXPublishParam *videoPublishParams = [[TXPublishParam alloc] init];
        videoPublishParams.signature  = sign;
        videoPublishParams.videoPath  = self.videoUrl.path;
        NSString *coverPath = [self getImagePathFromImage:objectID];
        videoPublishParams.coverPath = coverPath;
        [_videoPublish publishVideo:videoPublishParams];
    }];
}

- (NSString *)getImagePathFromImage:(UIImage *)image {
    
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *imageName = [[self fileKey] stringByAppendingString:@".jpg"];
    NSString *path = [documents stringByAppendingPathComponent:imageName];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    [imageData writeToFile:path atomically:YES];
    return path;
}


- (void)getCover:(double)x videoUrl:(NSURL *)url compelete:(void(^)(UIImage * objectID))compelete
{
    AVURLAsset *avset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVAssetImageGenerator *ImageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:avset]; // 缩略图
    ImageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
    ImageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
    ImageGenerator.appliesPreferredTrackTransform = YES;
    
    
    CMTime time = CMTimeMakeWithSeconds(x, 1000);
    dispatch_async(dispatch_get_main_queue(), ^{
        CGImageRef imageRef = [ImageGenerator copyCGImageAtTime:time actualTime:nil error:nil];
        UIImage *image = [UIImage imageWithCGImage:imageRef]; // 获取一张图片
        compelete(image);
        CGImageRelease(imageRef);
    });
}

#pragma mark -- 视频代理方法
- (void)onPublishProgress:(NSInteger)uploadBytes totalBytes: (NSInteger)totalBytes
{
    self.progressView.progress = (float)uploadBytes/totalBytes;
    NSString *precent = [NSString stringWithFormat:@"%.2f",(CGFloat)uploadBytes/totalBytes];
    NSInteger intValue = [precent floatValue] * 100;
    self.progressLabel.text = [NSString stringWithFormat:@"%ld%%",(long)intValue];
    NSLog(@"onPublishProgress [%ld/%ld]", (long)uploadBytes, (long)totalBytes);
}

- (void)onPublishComplete:(TXPublishResult*)result
{
    NSString *string = [NSString stringWithFormat:@"上传完成，错误码[%d]，信息[%@]", result.retCode, result.retCode == 0? result.videoURL: result.descMsg];
    NSLog(@"onPublishComplete [%d/%@]", result.retCode, result.retCode == 0? result.videoURL: result.descMsg);
    
    if (result.retCode == 0) {
        
        [self.progressView setProgress:1 animated:YES];
        
        self.progressLabel.hidden = YES;
        self.doneBtn.hidden = NO;
    }
}

- (NSString *)timestampStr {
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];  // 获取当前时间0秒后的时间
    NSTimeInterval time = [date timeIntervalSince1970] * 1000; // *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

- (NSString *)fileKey
{
    NSString *timeStr = [self timestampStr];
    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString *key = [adId stringByAppendingString:timeStr];
    return key;
}

@end
